package com.gcstorage.tvdev.base;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.gcstorage.tvdev.bean.H5AppInfo;
import com.gcstorage.tvdev.bean.H5ReqBean;
import com.gcstorage.tvdev.bean.MeetingInfoBean;
import com.gcstorage.tvdev.bean.UserInfo;
import com.gcstorage.tvdev.constants.AppConstant;
import com.gcstorage.tvdev.constants.Constant;
import com.gcstorage.tvdev.constants.GlobalConstants;
import com.gcstorage.tvdev.constants.KeyCode;
import com.gcstorage.tvdev.constants.LogCat;
import com.gcstorage.tvdev.net.H5RxObserver;
import com.gcstorage.tvdev.net.HttpClient;
import com.gcstorage.tvdev.util.EncodeUtils;
import com.gcstorage.tvdev.util.H5AppManager;
import com.gcstorage.tvdev.util.JumpHelper;
import com.gcstorage.tvdev.util.RxSimple;
import com.gcstorage.tvdev.util.SpUtils;
import com.gcstorage.tvdev.util.SpfAgent;
import com.gcstorage.tvdev.util.UserHelper;
import com.google.gson.Gson;
import com.google.gson.JsonElement;

import org.apache.commons.text.StringEscapeUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * H5对外接口
 */
public class BaseAndroidJSInterface {
    protected Context context;
    protected WebView view;
    private final String host;

    public BaseAndroidJSInterface(Context context, WebView view, String host) {
        this.context = context;
        this.view = view;
        this.host = host;
    }

    @JavascriptInterface
    public String getAppPath(String appId, String params) {
        return H5AppManager.getAppIdLocalUrl(appId, params);
    }

    @JavascriptInterface//网络请求
    public void gcRequest(String requestContent) {
        gcRequest("", requestContent);
    }

    @JavascriptInterface//网络请求
    public String gcRequest(String hostIp, String requestContent) {
        H5ReqBean request = JSON.parseObject(requestContent, H5ReqBean.class);
        // final H5ReqBean request = GsonUtils.fromJson(requestContent, H5ReqBean.class);
        if (TextUtils.isEmpty(request.getUrl())) {
            return "{错误提示}";
        }
        String method = request.getRequestMethod();
        HashMap<String, Object> headers = request.getHeader();
        String hostAddress = !TextUtils.isEmpty(hostIp) ? hostIp : this.host;
        switch (method.toUpperCase()) {
            case "GET":
                HttpClient.get().get(hostAddress + request.getUrl(), request.getParams(), headers, new H5RxObserver(request.getJsMethod(), view));
                break;
            case "POST":
                HttpClient.get().post(hostAddress + request.getUrl(), request.getParams(), headers, new H5RxObserver(request.getJsMethod(), view));
                break;
            case "BODY":
                HttpClient.get().postBody(hostAddress + request.getUrl(), request.getParams() == null || request.getParams().isEmpty()
                        ? StringEscapeUtils.unescapeJson(request.getBodyParams()) : GsonUtils.toJson(request.getParams()), headers, new H5RxObserver(request.getJsMethod(), view));
                break;
            case "UPLOAD":
                Observable.just(request.getBase64())
                        .subscribeOn(Schedulers.io())
                        .map(new Function<ArrayList<String>, List<String>>() {
                            @Override
                            public List<String> apply(ArrayList<String> base64List) throws Exception {
                                List<String> filePath = new ArrayList<>();

                                for (String item : base64List) {
                                    String file = GlobalConstants.IMAGE_DIR + "/IMG_" + System.currentTimeMillis() + ".png";
                                    FileUtils.createOrExistsFile(file);
                                    EncodeUtils.decoderBase64File(item, file);
                                    filePath.add(file);
                                }
                                return filePath;
                            }
                        }).flatMap(new Function<List<String>, ObservableSource<JsonElement>>() {
                    @Override
                    public ObservableSource<JsonElement> apply(List<String> strings) throws Exception {
                        return HttpClient.get().uploadPic(hostAddress + request.getUrl(), request.getParams(), strings, request.getHeader());
                    }
                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new H5RxObserver(request.getJsMethod(), view));
                break;
        }
        return "Success";
    }

    @JavascriptInterface
    public void back() {
        // Android返回上一页，关闭当前容器
        LogUtils.d(LogCat.LOG_COMMONON + " back");
//        LiveEventBus.get(EventChannel.EVENT_CHANNEL_NOTICE_BACK).post(true);
//        EventBus.getDefault().post(new CloseEvent(1));
    }

    @JavascriptInterface //从本地缓存 取出用户基本信息，转换为 json，提供给 h5使用
    public String getUserInfo() {
        UserInfo userInfo = UserHelper.instance().getUserInfo();
        String chatId = SpfAgent.getString(Constant.baseSpf, Constant.SP_KEY_chatId);//聊天id 即 猎鹰 用户id
        String equipmentId = SpfAgent.getString(Constant.baseSpf, Constant.SP_equipmentId);//设备ID

        ArrayMap<String, String> map = new ArrayMap<>();
        map.put("userInfo", new Gson().toJson(UserHelper.instance().getUserInfo()));
        map.put("userId", userInfo.getUserId());
        map.put("id", userInfo.getUserId());
        map.put("token", SpUtils.getString(SpUtils.TAG_USER, KeyCode.USER_ACCESS_TOKEN, ""));
        map.put("head_pic", userInfo.getAvatar());
        map.put("name", userInfo.getRealName());
        map.put("depart", userInfo.getDeptName());
        map.put("account", userInfo.getUserId());
        map.put("policenum", userInfo.getPoliceNo());
        map.put("orgid", userInfo.getDeptId());
        map.put("phone", userInfo.getPhone());
        map.put("chatId", chatId);
        map.put("equipmentId", equipmentId);
        map.put("mapBoxUrl", AppConstant.getMapBoxUrl());
        map.put("tenantId", SpUtils.getString("tenantId"));
        return GsonUtils.toJson(map);
    }

    @JavascriptInterface//获取设备号
    public String getAndroidId() {
        return DeviceUtils.getAndroidID();
    }

    @JavascriptInterface //获取app信息
    public String getAppInfo() {
        HashMap<String, Object> map = new HashMap<>();
        File file = new File("");
        map.put("app_version", AppUtils.getAppVersionCode());//版本标号 如：156312
        map.put("app_name", AppUtils.getAppVersionName());//版本名字 如:1.7.2
        map.put("app_equ_name", DeviceUtils.getManufacturer());//设备品牌
        map.put("app_equ_no", DeviceUtils.getModel());//设备型号
        map.put("app_equ_flag", DeviceUtils.getUniqueDeviceId());//唯一码
        return new Gson().toJson(map);
    }

    @JavascriptInterface
    public String getHost() {
        return AppConstant.getApiAddress();
    }

    @JavascriptInterface
    public void gotoH5(String url) {
        H5AppManager.getInstance().openAppByUrl(url);
    }

    @JavascriptInterface//工作台打开下载的H5应用
    public void openH5App(String json) {
        //json  返回本地h5对象
        if (RxSimple.isFastClick(800)) return;
        H5AppInfo h5AppInfo = new Gson().fromJson(json, H5AppInfo.class);
        if (h5AppInfo.getAppType().equals("10")) {
            String path = h5AppInfo.getPackageName().split("Action:")[1];
            JumpHelper.jumpReflex((Activity) context, null, path);
        } else if (h5AppInfo.getAppType().equals("20")) {
            H5AppManager.getInstance().openApp(h5AppInfo);
        } else if (h5AppInfo.getAppType().equals("30")) {
            if (AppUtils.isAppInstalled(h5AppInfo.getPackageName())) {
                if (TextUtils.equals("wpa.hubei.hjkc", h5AppInfo.getPackageName())) {
                    Intent intent = new Intent();
                    ComponentName cn = new ComponentName(h5AppInfo.getPackageName(), "wpa.hubei.xlpc.hjkc.rchc.RchcMainActivity2");
                    String identitycard = UserHelper.instance().getUserInfo().getIdCard();
                    intent.putExtra("lzy_sfzh", identitycard);
                    intent.setComponent(cn);
                    context.startActivity(intent);
                } else {
                    if (h5AppInfo.getPackageName().contains("gcstorage")) {
                        JumpHelper.jumpUrl((Activity) context, AppConstant.getGotoAppUrl(h5AppInfo.getPackageName()), AppConstant.getUserBundle());
                    } else {
                        JumpHelper.jumpPackageName(context, h5AppInfo.getPackageName());
                    }
                }
            } else {
                ToastUtils.showShort("请先安装" + h5AppInfo.getAppName());
            }
        } else if (h5AppInfo.getAppType().equals("50")) {
            JumpHelper.gotoH5Activity(context, h5AppInfo.getPackageName(), false, "", h5AppInfo);
        }
    }

    @JavascriptInterface//检测手机是否又此应用
    public boolean isAppInstalled(String packageName) {
        return AppUtils.isAppInstalled(packageName);
    }

    @JavascriptInterface//vue使用的log打印方法
    public void h5Log(String content) {
        LogUtils.d("h5Log", content);
    }

    @JavascriptInterface//通过appId下载
    public void h5AppDownload(String appId) {
        H5AppManager.getInstance().downloadAppByAppId(appId);
    }

    @JavascriptInterface
    public boolean h5AppIsExist(String appId) {
        return H5AppManager.getInstance().isExistApp(appId);
    }

    @JavascriptInterface//小鱼-参会
    public void meetingMakeCall(String json) {
        if (TextUtils.isEmpty(json)) {
            return;
        }
        MeetingInfoBean info = GsonUtils.fromJson(json, MeetingInfoBean.class);
//        EventBus.getDefault().post(new XyEvent("1", info));
    }

    @JavascriptInterface //返回app平台,小程序做不同显示
    public String getAppPlatform() {
        return "tv";
    }


}

